# Barry's Game Library - Smaller Version
# Copyright (C) 2009 - Barry "Ishara" Peddycord
# ishara@isharacomix.com
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# This is a collection of helpful functions created for the games I've
# released. Feel free to import and modify this library whenever you like.

import sys, os, math, re

import pygame
from pygame.locals import *

STORAGE = {}
SOUNDS = {}

# Takes an indefinite number of strings and creates an absolute file name
# reference.
def filename(*paths):
    pathway = os.path.abspath(os.path.dirname(__file__))
    pathway = os.path.normpath(os.path.join(pathway, ".."))
    for x in paths:
        pathway = os.path.normpath(os.path.join( pathway, str(x) ))
    return pathway

# Load a given font. Loads from an absolute pathname, so be sure to run
# filename(x) before calling this function.
def load_font(filename, size):
    return pygame.font.Font(filename, size)

# Loads an image and saves it in STORAGE. Note that this loads an absolute
# filename, so run filename(x) before calling this function. If the colorkey
# is -1, it autodetects the transparency by using the top-left pixel of the image.
def load_storage(name, colorkey=None):
    if name not in STORAGE:
        try: STORAGE[name] = pygame.image.load(name)
        except pygame.error, message:
            print("Cannot load image:", name)
            raise SystemExit, message
        if colorkey == -2:
            STORAGE[name] = STORAGE[name].convert_alpha()
        else:
            STORAGE[name] = STORAGE[name].convert()
            if colorkey is not None:
                if colorkey is -1:
                    colorkey = STORAGE[name].get_at((0,0))
                STORAGE[name].set_colorkey(colorkey, RLEACCEL)
    return STORAGE[name]

# A dummy sound that simply pretends to be a sound. This allows you to play
# a game with optional sound files that don't necessarily have to be in the
# game's packaging.
class DummySound(object):
    def fadeout(self, *args): pass
    def get_buffer(self, *args): return None
    def get_length(self, *args): return 0
    def get_num_channels(self, *args): return 0
    def get_volume(self, *args): return 0
    def play(self, *args): pass
    def set_volume(self, *args): pass
    def stop(self, *args): pass
DUMMY = DummySound()

# This creates a sound and then saves it in a dictionary named SOUNDS
# (similar to the load_storage method). Use this for small sound effects
# that are going to be used over and over again, but be conservative
# with your usage to avoid using up too much memory.
def get_storage(name):
    if not pygame.mixer or not pygame.mixer.get_init():
        return DUMMY
    if name not in SOUNDS:
        try: sound = pygame.mixer.Sound(name)
        except:
            return DUMMY
            print("Cannot load sound:", name)
        SOUNDS[name] = sound
    return SOUNDS[name]

# Returns a wordwrapped list of strings in the given font over a particular
# amount of space.
def wordwrap(words, f, sz):
    lines = words.split("\n")
    v = []
    for l in lines:
        st = 0
        en = len(l)
        while st < en:
            if f.size(l[st:en])[0] < sz:
                v.append(l[st:en])
                st = en+1
                en = len(l)
            else:
                en = l.rfind(" ",st,en)
        if l[st:].strip() != "":
            v.append(l[st:])
    if v == []: v = [""]
    return v
